package main

import (
	"fmt"
	"os"
	"path/filepath"
	//"strconv"
	"bytes"
	"io/ioutil"
	"strings"
)

func WalkDir(dirPth, suffix string) (files []string, err error) {
	files = make([]string, 0, 30)
	suffix = strings.ToUpper(suffix)                                                     //忽略后缀匹配的大小写
	err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { //遍历目录
		if fi.IsDir() { // 忽略目录
			return nil
		}
		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
			files = append(files, filename)
		}
		return nil
	})
	return files, err
}

func getJsonFiles(path string) []string {
	files := make([]string, 0, 0)
	xlsx, err := WalkDir(path, ".json")
	if err == nil {
		files = append(files, xlsx...)
	}
	return files
}

func Substr(str string, start int, end int) string {
	rs := []rune(str)
	length := len(rs)
	if start < 0 {
		start = 0
	}

	if start < 0 || start > length {
		panic("start is wrong")
	}

	if end <= 0 {
		end = length
	}
	if end > length {
		panic("end is wrong")
	}

	return string(rs[start:end])
}

func Readfile(filePath string) ([]byte, error) {
	//读取文件
	fi, err := os.Open(filePath)
	defer fi.Close()
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(fi)
}

func readJsonFiles(files []string) string {
	buf := bytes.NewBuffer([]byte("var jsonObj = {"))
	for i, fileName := range files {
		//读取文件
		data, _ := Readfile(fileName)
		key := Substr(fileName, strings.LastIndex(fileName, "\\")+1, strings.LastIndex(fileName, "."))
		str := string(data)
		str = strings.Replace(str, "\r", "", 99)
		str = strings.Replace(str, "\n", "", 99)
		if i != 0 {
			buf.WriteString(",")
		}
		buf.WriteString("\"")
		buf.WriteString(key)
		buf.WriteString("\":")
		buf.WriteString(str)
	}
	buf.WriteString(" };")
	return buf.String()
}

func getPureMainJsFile(fileName string) string {
	data, _ := Readfile(fileName)
	str := string(data)
	lines := strings.Split(str, "\n")
	buf := bytes.NewBufferString("")
	isStart := false
	//逐行读取，直到我们想要的那一行，将后面的保存并返回
	for _, line := range lines {
		if isStart == false && strings.Index(line, "(function ()") == 0 {
			isStart = true
		}
		if isStart {
			buf.WriteString(line + "\n")
		}
	}
	pureStr := buf.String()
	return pureStr
}

func WriteFile(filePath, data string, isAppend bool) bool {
	var f *os.File = nil
	if isAppend {
		//创建文件
		file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, os.ModePerm|os.ModeTemporary)
		if err != nil {
			fmt.Println(err.Error())
			return false
		}
		f = file
	} else {
		//删除原来的文件
		os.Remove(filePath)
		//创建文件
		file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, os.ModePerm|os.ModeTemporary)
		if err != nil {
			fmt.Println(err.Error())
			return false
		}
		f = file
	}
	f.WriteString(data)
	f.Close()
	return true
}

func main() {
	//relativePath := "../../vr/build/web-mobile/";
	relativePath := "./";
	if len(os.Args)>1{
		fmt.Println(os.Args[1]);
		relativePath=os.Args[1];
	}
	fmt.Println("version 1.0.0");
	fmt.Println(relativePath);

	jsonPath := relativePath;
	mainjsPath := relativePath + "main.js";
	cocosjsPath := relativePath + "cocos2d-js-min.js";
	//查询所有json文件
	files := getJsonFiles(jsonPath)
	//将他们读到一起，组成一个字符串
	jsonObj := readJsonFiles(files)
	//获得main.js文件里面的原始内容。过滤掉我们自己添加的东西，避免重复添加
	pureMain := getPureMainJsFile(mainjsPath)
	//将以上这些写入到main.js中
	buf := bytes.NewBufferString("")
	buf.WriteString(jsonObj)
	buf.WriteString("\r\n")
	buf.WriteString("\r\n")
	buf.WriteString("window.inner_downloadText = function (item, callback) {\r\n	if (item.type === \"uuid\") {\r\n		if (jsonObj[item.uuid]) {\r\n			callback(null, jsonObj[item.uuid]);\r\n		} else if (jsonObj[item.id]) {\r\n			callback(null, jsonObj[item.id]);\r\n		}\r\n  		return true;\r\n	}\r\n	return false;\r\n};")
	buf.WriteString("\r\n")
	buf.WriteString("\r\n")
	buf.WriteString(pureMain)
	WriteFile(mainjsPath, buf.String(), false)

	//读取cocos2d-js-min.js文件
	minData, _ := Readfile(cocosjsPath)
	minStr := string(minData)
	//如果没有我们想要添加的字符串，那就添加上
	if strings.Index(minStr, "if(window.inner_downloadText(t,e)) {return;};") == -1 {
		minStr = strings.Replace(minStr, "var i=t.url,r=f.getXMLHttpRequest()", "if(window.inner_downloadText(t,e)) {return;};var i=t.url,r=f.getXMLHttpRequest()", 1)
		WriteFile(cocosjsPath, minStr, false)
	}
}
